import { ref } from 'vue'
import { useMessageStore } from '@/stores/messageStore'
import { useModalStore } from '@/stores/modalStore'
import type { MsgLogs, ErrorData } from '@/types/loginType'
import { useCurrActStroe } from '@/stores/currActStore'
import { useAsyncAxios } from '@/utils/asyncFuncStore'
import { storeToRefs } from 'pinia'
import { useSocketStore } from '@/stores/socketStore'
import useUrtToImg from '@/utils/urlToImg'
export default function () {
  // 发送消息
  const textarea = ref<HTMLTextAreaElement | null>(null)

  const postTextareaData = new FormData()

  async function sendMessage() {
    if (textarea.value !== null) {
      const text = textarea.value.innerHTML
      const regex = /<img[^>]*>/g
      const replacedText = text.replace(regex, (match) => {
        // 使用正则表达式从img标签中提取src属性值
        const srcRegex = /src="([^"]*)"/
        const srcMatch = match.match(srcRegex)
        if (srcMatch && srcMatch[1]) {
          // 返回src属性值
          return srcMatch[1]
        }
        // 如果无法匹配src属性，返回原始匹配项
        return match
      })

      textarea.value.innerText = ''
      // 解析链接
      const { currUser } = storeToRefs(useCurrActStroe())
      postTextareaData.set('sendId', currUser.value.id)
      postTextareaData.set('content', replacedText)
      const { userTarget } = storeToRefs(useMessageStore())
      postTextareaData.set('sendTo', userTarget.value.id)

      const { addLogsData } = useMessageStore()
      const { postMessageToUser } = useAsyncAxios()
      const { status, data } = await postMessageToUser(postTextareaData)

      if (status === 200) {
        // 发送成功
        const result = data as MsgLogs
        const { id, content, time, acceptId } = result
        result.time = new Date(time).toLocaleTimeString().substring(0, 5)
        addLogsData(result as MsgLogs)
        const { sendMessage } = useSocketStore()
        sendMessage(acceptId, content || null)
      } else {
        // 发送失败
        const { changeData } = useModalStore()
        changeData({ status, data: data as ErrorData })
      }
    }
  }
  // 解析 粘贴板
  function readerPaste(event: ClipboardEvent) {
    const clipboardData = event.clipboardData || (window as any).clipboardData
    const url: string = clipboardData.getData('text')
    const regex = /https?:\/\/[^\s]+(\.jpg|\.jpeg|\.png|\.gif|\.bmp|\.webp)/gi
    if (url.match(regex)) {
      event.preventDefault()

      const imgElement = new Image()
      imgElement.src = url + ' '
      if (textarea.value) {
        textarea.value.appendChild(imgElement)
        if (textarea.value.value) {
          textarea.value.value += url
        } else {
          textarea.value.value = url
        }
      }
      const { setWidth } = useUrtToImg()
      const [width, height] = setWidth(imgElement, 100)
      imgElement.width = width
      imgElement.height = height
    }

    setTimeout(() => {
      const range = document.createRange()
      const sel = window.getSelection()
      range.setStart(textarea.value as Node, (textarea.value as Node).childNodes.length)
      range.collapse(true)
      if (sel) {
        sel.removeAllRanges()
        sel.addRange(range)
      }
    }, 0)
  }
  return {
    textarea,
    sendMessage,
    readerPaste
  }
}
